package com.gc.ykqx.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aitangba.pickdatetime.DatePickDialog;
import com.aitangba.pickdatetime.OnSureListener;
import com.aitangba.pickdatetime.bean.DateParams;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.Polyline;
import com.amap.api.maps2d.model.PolylineOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.gc.ykqx.R;
import com.gc.ykqx.service.entity.GridItem;
import com.gc.ykqx.service.entity.Pimp;
import com.gc.ykqx.service.entity.Site;
import com.gc.ykqx.service.entity.SiteResponse;
import com.gc.ykqx.service.entity.WeaResponse;
import com.gc.ykqx.service.presenter.QySitePresenter;
import com.gc.ykqx.service.presenter.QyWeaPresenter;
import com.gc.ykqx.service.presenter.SwSitePresenter;
import com.gc.ykqx.service.presenter.SwWeaPresenter;
import com.gc.ykqx.service.util.Constant;
import com.gc.ykqx.service.util.DataParse;
import com.gc.ykqx.service.util.DateUtil;
import com.gc.ykqx.service.util.ParseUtil;
import com.gc.ykqx.service.view.QySiteView;
import com.gc.ykqx.service.view.QyWeaView;
import com.gc.ykqx.service.view.SwSiteView;
import com.gc.ykqx.service.view.SwWeaView;
import com.gc.ykqx.ui.CountActivity;
import com.gc.ykqx.ui.DetailsActivity;
import com.gc.ykqx.ui.custom.LazyFragment;
import com.gc.ykqx.ui.custom.TabView;
import com.victor.loading.rotate.RotateLoading;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * 实况
 * 我不管其他的 我要做的事情只有两件
 * 1.选择完成后 调用网络请求(传给他id)
 * 2.网络加载完成后 显示结果
 */
public class LiveFragment extends LazyFragment implements AMap.OnInfoWindowClickListener, AMap.OnMarkerClickListener, AMap.OnMapClickListener, TabView.OnFinishChooseListener, View.OnClickListener {
    @BindView(R.id.tab_view)
    TabView tabView;//自定义菜单栏
    @BindView(R.id.op_layout)
    LinearLayout opLayout;//前后翻区域
    @BindView(R.id.tv_title)
    TextView tvTitle;//显示标题
    @BindView(R.id.map_view)
    MapView mapView;//地图
    @BindView(R.id.tv_maker)
    TextView tvMaker;//标记点
    @BindView(R.id.rotateloading)
    RotateLoading rotateloading;//加载动画控件
    Unbinder unbinder;
    @BindView(R.id.btn_previous)
    ImageButton btnPre;
    @BindView(R.id.btn_next)
    ImageButton btnNext;
    @BindView(R.id.update_layout)
    RelativeLayout updateLayout;
    private static final String TAG = "LiveFragment";


    private Context mContext;
    private QySitePresenter qySitePresenter;
    private SwSitePresenter swSitePresenter;
    private QyWeaPresenter qyWeaPresenter;
    private SwWeaPresenter swWeaPresenter;
    private AMap aMap;//地图
    private Marker showInfoWindowMaker;//当前显示的maker
    private ArrayList<Site> qySites;//区域站
    private ArrayList<Site> swSites;//水文站
    private String qyStaIds;//区域站号集
    private String swStaIds;//水文站号集
    private List<Pimp> pimpList;//
    String selectId;//选择Id
    String siteType;//站号类型
    private String timeType;//时间类型
    private String nameAfterTime;//显示时间后面的标题
    private String special;//special mark
    private String requestTime;//请求时间
    private String showTime;//显示时间
    private boolean isPrepared;//控件准备完成
    private boolean isLoaded;//是否初始化过
    private boolean isGot;//是否加载过
    private PopupWindow pw;
    private String diyType;
    private String beginTime;
    private String endTime;

    public LiveFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mapView != null) {
            mapView.onDestroy();
        }
        unbinder.unbind();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_live, container, false);
        unbinder = ButterKnife.bind(this, view);
        mapView.onCreate(savedInstanceState);
        init();
        isPrepared = true;
        lazyLoad();
        return view;
    }

    private void init() {
        //初始化
        mContext = getContext();
        qySitePresenter = new QySitePresenter(mContext);
        qySitePresenter.onCreate();
        qySitePresenter.attachView(qySiteView);
        swSitePresenter = new SwSitePresenter(mContext);
        swSitePresenter.onCreate();
        swSitePresenter.attachView(swSiteView);
        qyWeaPresenter = new QyWeaPresenter(mContext);
        qyWeaPresenter.onCreate();
        qyWeaPresenter.attachView(qyWeaView);
        swWeaPresenter = new SwWeaPresenter(mContext);
        swWeaPresenter.onCreate();
        swWeaPresenter.attachView(swWeaView);
        aMap = mapView.getMap();
        tabView.setOnFinishChooseListener(LiveFragment.this);
        qySites = new ArrayList<>();
        swSites = new ArrayList<>();
        pimpList = new ArrayList<>();
        String[] selectIdArray = getResources().getStringArray(R.array.selectIdItem);
        String[] siteTypeArray = getResources().getStringArray(R.array.siteTypeItem);
        String[] timeTypeArray = getResources().getStringArray(R.array.timeTypeItem);
        String[] specialArray = getResources().getStringArray(R.array.specialItem);
        String[] nameAfterTimeArray = getResources().getStringArray(R.array.nameAfterTimeItem);
        for (int i = 0; i < selectIdArray.length; i++) {
            Pimp pimp = new Pimp();
            pimp.setSelectId(selectIdArray[i]);
            pimp.setSiteType(siteTypeArray[i]);
            pimp.setTimeType(timeTypeArray[i]);
            pimp.setSpecial(specialArray[i]);
            pimp.setNameAfterTime(nameAfterTimeArray[i]);
            pimpList.add(pimp);
            if (i == 0) {
                getMenuInfo(pimp);
            }
        }
    }

    /*
    set pimp's value
     */
    private void getMenuInfo(Pimp pimp) {
        selectId = pimp.getSelectId();
        siteType = pimp.getSiteType();
        timeType = pimp.getTimeType();
        requestTime = DateUtil.getNewTime(timeType);
        nameAfterTime = pimp.getNameAfterTime();
        special = pimp.getSpecial();
    }

    /*
   懒加载
    */
    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || isLoaded) {
            return;
        }
        rotateloading.start();
        qySitePresenter.getQySite();
        setBorder();
        isLoaded = true;
    }

    private QySiteView qySiteView = new QySiteView() {
        @Override
        public void onSuccess(SiteResponse response) {
            if (response.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                Log.e(TAG, "区域站->: " + response.toString());
                qyStaIds = DataParse.parseSite(qySites, response.getDS(), siteType);
               /* for (int i = 0; i < qySites.size(); i++) {
                    Site site = qySites.get(i);
                    if (!site.getStationId().equals("K6110")) {
                        qySites.remove(i);
                        i--;
                    }
                    Log.e(TAG, "" + site.getStationId() + " " + site.getStation_name() + " " + site.getLat() + " " + site.getLon());
                }*/
                qyWeaPresenter.getWeather(selectId, qyStaIds, requestTime, siteType, beginTime, endTime, diyType);
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError:qySiteView-> " + result);
        }
    };
    private SwSiteView swSiteView = new SwSiteView() {
        @Override
        public void onSuccess(SiteResponse response) {
            if (response.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                Log.e(TAG, "水文站->: " + response.toString());
                swStaIds = DataParse.parseSite(swSites, response.getDS(), siteType);
                swWeaPresenter.getWeather(selectId, swStaIds, requestTime, siteType, beginTime, endTime, diyType);
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "onError:SwSiteView-> " + result);
        }
    };

    private QyWeaView qyWeaView = new QyWeaView() {
        @Override
        public void onSuccess(WeaResponse weaResponse) {
            Log.e(TAG, "qyWeaView->onSuccess: " + weaResponse.getReturnMessage());
            if (rotateloading != null) {
                rotateloading.stop();
            }
            try {
                if (weaResponse.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                    DataParse.parseWea(qySites, weaResponse.getDS(), requestTime, selectId, timeType, special, diyType);
                } else {
                    DataParse.clearValue(qySites);
                }
                setWea();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "qyWeaView>onError: " + result);
        }
    };

    private SwWeaView swWeaView = new SwWeaView() {
        @Override
        public void onSuccess(WeaResponse weaResponse) {
            Log.e(TAG, "swWeaView->onSuccess: " + weaResponse.getReturnMessage());
            if (rotateloading != null) {
                rotateloading.stop();
            }
            try {
                if (weaResponse.getReturnCode() == Constant.Response.SUCCESS_CODE) {
                    DataParse.parseWea(swSites, weaResponse.getDS(), requestTime, selectId, timeType, special, diyType);
                } else {
                    DataParse.clearValue(swSites);
                }
                setWea();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(String result) {
            Log.e(TAG, "swWeaView>onError: " + result);
        }
    };

    /*
    set wea
    1.title
    2.setMarker
     */
    private void setWea() { // TODO: 2017/10/6 all sw will be cover qy title
        if (selectId.equals("n16") || selectId.equals("n24") || selectId.equals("n34")) {
            requestTime = DateUtil.subTime(requestTime, timeType);//20点以来显示减去一天
        }
        showTime = DateUtil.getShowTime(requestTime, timeType);
        if (special.equals(Constant.Special.DIY)) {
            tvTitle.setText(DateUtil.getShowTime(beginTime, diyType) + "至" + DateUtil.getShowTime(endTime, diyType) + nameAfterTime);
        } else {
            tvTitle.setText(showTime + nameAfterTime);
        }
        List<Site> mSiteList = new ArrayList<>();
        switch (siteType) {
            case Constant.SiteType.SITE_QY:
                mSiteList = qySites;
                break;
            case Constant.SiteType.SITE_SW:
                mSiteList = swSites;
                break;
            case Constant.SiteType.SITE_ALL: // TODO: 2017/10/6  should qy and sw
                mSiteList.addAll(qySites);
                mSiteList.addAll(swSites);
                break;
        }
        setMaker(mSiteList);//请求成功,打点
    }

    /*
    set marker on map
     */
    private void setMaker(List<Site> mSiteList) {
        removeAllMarker();
        for (int i = 0; i < mSiteList.size(); i++) {
            Site mSite = mSiteList.get(i);
            LatLng latLng = new LatLng(Double.parseDouble(mSite.getLat()), Double.parseDouble(mSite.getLon()));
            if (mSite != null) {
                String sId = mSite.getStationId();
                String value = mSite.getValue();
                if (TextUtils.isEmpty(value)) {
                    if (selectId.equals("n10") && DateUtil.getNewTime(Constant.Time.TIME_MIN).equals(requestTime)) {
                        value = ".";
                    } else {
                        value = Constant.NO_DATA_FLAG;
                    }
                } else if (selectId.contains("n1") || selectId.contains("n2") || selectId.contains("n3")) {
                    if (Double.parseDouble(value) <= 0) {
                        value = Constant.NO_PRE_FLAG;
                    }
                }
                tvMaker.setText(value);
                if (sId.equals("58654") || sId.equals("K9021") || sId.equals("K9078") || sId.equals("K9074") || sId.equals("K9008") ) {
                    tvMaker.setBackgroundColor(Color.parseColor("#FB964B"));
                } else if (sId.equals("58642") || sId.equals("K6104") || sId.equals("K6183") || sId.equals("K6044") || sId.equals("K6184")|| sId.equals("K6072")) {
                    tvMaker.setBackgroundColor(Color.parseColor("#92D050"));
                } else {
                    tvMaker.setBackgroundColor(Color.parseColor("#4FC0E8"));
                }
                Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).
                        title(mSite.getStation_name()).
                        snippet(value).
                        draggable(false).
                        icon(BitmapDescriptorFactory.fromBitmap(loadBitmapFromView(tvMaker, sId))));
            }
        }
    }

    /*
    前翻 后翻 统计按钮的监听事件
   */
    @OnClick({R.id.btn_previous, R.id.btn_next, R.id.btn_count})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_previous:
                requestTime = DateUtil.subTime(requestTime, timeType);
                getWea();
                break;
            case R.id.btn_next:
                String result = DateUtil.addTime(requestTime, timeType);
                if (result == null) {//out current time
                    Toast.makeText(mContext, Constant.OUT_TIME, Toast.LENGTH_SHORT).show();
                } else {
                    requestTime = result;
                    getWea();
                }
                break;
            case R.id.btn_count:
                goCountAty();
                break;
        }
    }

    /*
    if get wea by time >set wea
    else > load wea
     */
    private void getWea() {
        switch (siteType) {
            case Constant.SiteType.SITE_QY:
                isGot = ParseUtil.getWea(qySites, requestTime);//contain clear value
                break;
            case Constant.SiteType.SITE_SW:
                isGot = ParseUtil.getWea(swSites, requestTime);//contain clear value
                break;
            case Constant.SiteType.SITE_ALL: // TODO: 2017/10/6  should qy and sw
                isGot = ParseUtil.getWea(qySites, requestTime);//contain clear value
                break;
        }
        if (isGot) {
            setWea();
        } else {
            loadWea();
        }
    }

    /*
    load wea by site type
     */
    private void loadWea() {
        rotateloading.start();
        switch (siteType) {
            case Constant.SiteType.SITE_QY:
                qyWeaPresenter.getWeather(selectId, qyStaIds, requestTime, siteType, beginTime, endTime, diyType);
                break;
            case Constant.SiteType.SITE_SW:
                swWeaPresenter.getWeather(selectId, swStaIds, requestTime, siteType, beginTime, endTime, diyType);
                break;
            case Constant.SiteType.SITE_ALL:
                qyWeaPresenter.getWeather(selectId, qyStaIds, requestTime, siteType, beginTime, endTime, diyType);
                swWeaPresenter.getWeather(selectId, swStaIds, requestTime, siteType, beginTime, endTime, diyType);
                break;
        }
    }

    /*
    进入统计页面
     */
    private void goCountAty() {
        if (showInfoWindowMaker != null) {
            showInfoWindowMaker.hideInfoWindow();
        }
        Intent intent = new Intent(getContext(), CountActivity.class);
        switch (siteType) {
            case Constant.SiteType.SITE_QY:
                intent.putExtra(Constant.TransmissionKey.SITE_LIST, qySites);
                break;
            case Constant.SiteType.SITE_SW:
                intent.putExtra(Constant.TransmissionKey.SITE_LIST, swSites);
                break;
            case Constant.SiteType.SITE_ALL:
                ArrayList<Site> siteList = new ArrayList<>();
                siteList.addAll(qySites);
                siteList.addAll(swSites);
                intent.putExtra(Constant.TransmissionKey.SITE_LIST, siteList);
                break;
        }
        intent.putExtra(Constant.TransmissionKey.TITLE, showTime + nameAfterTime);
        intent.putExtra(Constant.TransmissionKey.SITE_TYPE, siteType);
        startActivity(intent);
    }

    /*
    点菜
     */
    @Override
    public void onFinishChosen(String id) {
        removeAllMarker();
        if (id.equals("n50")) {
            updateLayout.setVisibility(View.VISIBLE);
        } else {
            updateLayout.setVisibility(View.GONE);
        }
        for (Pimp pimp : pimpList) {
            if (pimp.getSelectId().equals(id)) {
                if (pimp.getSpecial().equals(Constant.Special.ONLY_ONE) || pimp.getSpecial().equals(Constant.Special.DIY)) {
                    btnPre.setVisibility(View.GONE);
                    btnNext.setVisibility(View.GONE);
                } else {
                    btnPre.setVisibility(View.VISIBLE);
                    btnNext.setVisibility(View.VISIBLE);
                }
                getMenuInfo(pimp);
                break;
            }
        }
        if (special.equals(Constant.Special.DIY)) {//任意时段
            createPw();
        } else {
            requestTime = DateUtil.getNewTime(timeType);//reset requestTime
            rotateloading.start();
            switch (siteType) {
                case Constant.SiteType.SITE_QY:
                    DataParse.resetSites(qySites);//reset current value
                    if (TextUtils.isEmpty(qyStaIds)) {
                        qySitePresenter.getQySite();
                    } else {
                        qyWeaPresenter.getWeather(selectId, qyStaIds, requestTime, siteType, beginTime, endTime, diyType);
                    }
                    break;
                case Constant.SiteType.SITE_SW:
                    DataParse.resetSites(swSites);//reset current value
                    if (TextUtils.isEmpty(swStaIds)) {
                        swSitePresenter.getSwSite();
                    } else {
                        swWeaPresenter.getWeather(selectId, swStaIds, requestTime, siteType, beginTime, endTime, diyType);
                    }
                    break;
                case Constant.SiteType.SITE_ALL:
                    DataParse.resetSites(qySites);//reset current value
                    DataParse.resetSites(swSites);//reset current value
                    if (TextUtils.isEmpty(qyStaIds)) {
                        qySitePresenter.getQySite();
                    } else {
                        qyWeaPresenter.getWeather(id, qyStaIds, requestTime, siteType, beginTime, endTime, diyType);
                    }
                    if (TextUtils.isEmpty(swStaIds)) {
                        swSitePresenter.getSwSite();
                    } else {
                        swWeaPresenter.getWeather(selectId, swStaIds, requestTime, siteType, beginTime, endTime, diyType);
                    }
                    break;
            }
        }
    }

    private void createPw() {
        //设置contentView
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.popuplayout, null);
        pw = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pw.setContentView(contentView);
        //设置各个控件的点击响应
        TextView popDay = (TextView) contentView.findViewById(R.id.pop_day);
        TextView popHor = (TextView) contentView.findViewById(R.id.pop_hor);
        TextView popMin = (TextView) contentView.findViewById(R.id.pop_min);
        popDay.setOnClickListener(LiveFragment.this);
        popHor.setOnClickListener(LiveFragment.this);
        popMin.setOnClickListener(LiveFragment.this);
        //显示PopupWindow
        View rootview = LayoutInflater.from(mContext).inflate(R.layout.fragment_live, null);
        pw.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.pop_day) {
            diyType = Constant.Diy.DAY;
            showDatePickDialog(DateParams.STYLE_DAY);
            pw.dismiss();
        } else if (v.getId() == R.id.pop_hor) {
            diyType = Constant.Diy.Hor;
            showDatePickDialog(DateParams.STYLE_HOR);
            pw.dismiss();
        } else if (v.getId() == R.id.pop_min) {
            diyType = Constant.Diy.MIN;
            showDatePickDialog(DateParams.STYLE_MIN);
            pw.dismiss();
        }
    }

    private void showDatePickDialog(@DateParams.Style int style) {
        Calendar todayCal = Calendar.getInstance();
        Calendar startCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        endCal.add(Calendar.YEAR, 6);

        new DatePickDialog.Builder(style)
                .setCurrentDate(todayCal.getTime())
                .setStartDate(startCal.getTime())
                .setEndDate(endCal.getTime())
                .setOnSureListener(new OnSureListener() {
                    @Override
                    public void onSure(Date date, String type) {
                        String message = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
                        message = DateUtil.getFormatTimeByType(message, diyType);
                        if (type.equals(Constant.START_TIME)) {
                            beginTime = message;
                        } else if (type.equals(Constant.END_TIME)) {
                            endTime = message;
                            Log.e(TAG, "onSure: " + beginTime + " " + endTime);
                            if (Long.parseLong(beginTime) > Long.parseLong(endTime) || Long.parseLong(endTime) > Long.parseLong(DateUtil.getNewTime(Constant.Time.TIME_MIN))) {
                                Toast.makeText(mContext, "无效的时间", Toast.LENGTH_SHORT).show();
                                return;
                            } else if (Long.parseLong(beginTime) < Long.parseLong(endTime) || diyType.equals(Constant.Diy.Hor)) {
                                beginTime = DateUtil.addTime(beginTime, Constant.Time.TIME_HOR);
                            }
                            Log.e(TAG, "onSure: " + beginTime + " " + endTime);
                            loadWea();
                        }
                    }
                }).show(mContext);
    }

    private void setBorder() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Constant.CENTER_LAT, Constant.CENTER_LON), 11));//定位溪岸
        DistrictSearch search = new DistrictSearch(getContext());
        DistrictSearchQuery query = new DistrictSearchQuery();
        query.setKeywords(Constant.YK_NAME);//传入关键字
        query.setShowBoundary(true);//是否返回边界值
        search.setQuery(query);
        search.setOnDistrictSearchListener(new DistrictSearch.OnDistrictSearchListener() {
                                               @Override
                                               public void onDistrictSearched(DistrictResult districtResult) {
                                                   if (districtResult.getAMapException().getErrorCode() == 1000) {//查询成功
                                                       DistrictItem districtItem = districtResult.getDistrict().get(0);//行政区域对象
                                                       LatLonPoint center = districtItem.getCenter();//区域中心位置 即查询条件
                                                       //取出边界值 解析
                                                       String s = districtItem.districtBoundary()[0];
                                                       String[] groups = s.split(";");
                                                       List<LatLng> latLngs = new ArrayList<LatLng>();
                                                       for (int j = 0; j < groups.length; j++) {
                                                           String[] group = groups[j].split(",");
                                                           latLngs.add(new LatLng(Double.parseDouble(group[1]), Double.parseDouble(group[0])));
                                                       }
                                                       //根据值 画出边界线 设置边界线的属性
                                                       Polyline polyline = aMap.addPolyline(new PolylineOptions().
                                                               addAll(latLngs).width(10).color(Color.argb(255, 1, 1, 1)));
                                                       polyline.setColor(Color.argb(255, 132, 154, 189));
                                                   }
                                               }
                                           }

        );
        aMap.setOnInfoWindowClickListener(LiveFragment.this);
        aMap.setOnMarkerClickListener(LiveFragment.this);
        aMap.setOnMapClickListener(LiveFragment.this);
        search.searchDistrictAsyn();//开始搜索
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (showInfoWindowMaker != null) {
            showInfoWindowMaker.hideInfoWindow();
        }
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        } else {
            marker.showInfoWindow();
            showInfoWindowMaker = marker;
        }
        return true;
    }

    // TODO: 2017/10/6  I will check this method
    @Override
    public void onInfoWindowClick(Marker marker) {
        if (showInfoWindowMaker != null) {
            showInfoWindowMaker.hideInfoWindow();
        }
        String title = marker.getTitle();//marker的title
        ArrayList<GridItem> gridItemList = new ArrayList<>();//24小时集合
        for (int i = 0; i < qySites.size(); i++) {
            Site site = qySites.get(i);
            GridItem gridItem = new GridItem();
            gridItem.setSiteId(site.getStationId());
            gridItem.setName(site.getStation_name());
            if (site.getStation_name().equals(title)) {
                gridItem.setChecked(true);
            } else {
                gridItem.setChecked(false);
            }

            gridItemList.add(gridItem);
        }
        Intent intent = new Intent(getContext(), DetailsActivity.class);
        intent.putExtra(Constant.TransmissionKey.ITEM_LIST, gridItemList);
        intent.putExtra(Constant.TransmissionKey.SELECT_ID, selectId);
        startActivity(intent);
    }

    private void removeAllMarker() {
        List<Marker> markers = aMap.getMapScreenMarkers();
        for (Marker marker : markers) {
            if (marker != null) {
                marker.remove();
            }
        }
    }

    /*
    把textView生成图片
    */
    public Bitmap loadBitmapFromView(View v, String sId) {
        int w = v.getMeasuredWidth();
        int h = v.getMeasuredHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        v.layout(0, 0, w, h);
        v.draw(canvas);
        return bitmap;
    }
}